package main.java;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet(name = "HttpDownloadServlet", urlPatterns = "/servlet/HttpDownloadServlet")
public class HttpDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    RandomAccessFile randomAccessFile;
    OutputStream out;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        //要下载的文件
        File downloadFile = new File("D:/BaiduNetdiskDownload/08_queue模拟.mp4");
        //暂存容器
        byte bytes[] = new byte[1024];
        response.reset();
        try {
            response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFile.getName() + "\"");
            response.setContentType(CommonUtil.setContentType(downloadFile.getName()));
            response.addHeader("Content-Length", String.valueOf(downloadFile.length()));
            OutputStream outputStream = response.getOutputStream();
            out = new BufferedOutputStream(outputStream);
            randomAccessFile  = new RandomAccessFile(downloadFile, "r");
            int n = 0;
            while ((n = randomAccessFile.read(bytes, 0, 1024)) != -1) {
                out.write(bytes, 0, n);
            }
            out.flush();
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    System.err.println(e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println(e);
                }
            }
        }
    }
}